//业务列表 轻度封装根据传入pageName判断显示需要的组件
<template>
  <!-- 业务列表 -->
  <div class="flex-column">
    <div class="flex justify-between flex-row-reverse">
      <div class="text-right flex flex-wrap justify-end">
        <el-input
          v-model.trim="queryData.keyword"
          v-filterCharacter
          style="width: 200px"
          class="mb-10"
          maxlength="32"
          clearable
          :placeholder="$t('SERVICE_NAME') + '/' + $t('SERVICE_CODE')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-select
          v-model="queryData.bizStatus"
          clearable
          style="width: 200px"
          class="ml-10 mb-10"
          :placeholder="$t('SERVICE_STATUS')"
        >
          <el-option
            v-for="item in dictList.BIZ_STATUS"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
        <el-select
          v-model="stationType"
          clearable
          style="width: 200px"
          class="ml-10 mb-10"
          :placeholder="$t('SELECT_STATION')"
          @change="selectedIds = []"
        >
          <el-option value="no" :label="$t('NOT_A_Z')" />
          <el-option value="a" :label="$t('TRANS_DIRECT_START')" />
          <el-option value="z" :label="$t('TRANS_DIRECT_END')" />
        </el-select>
        <!-- 区域选择 -->
        <!-- 全部区域 -->
        <region-cascader
          v-show="stationType == 'no' || stationType == ''"
          style="width: 280px"
          class="ml-10 mb-10"
          :multiple="true"
          :selected-ids="selectedIds"
          @change="stationChange"
        />
        <!-- 占位用 -->
        <div v-show="stationType == 'no' || stationType == ''" style="width: 280px" />
        <!-- A端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          style="width: 280px"
          class="ml-10 mb-10"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'A_END_STATION_NAME' : 'Z_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? aStationChange(val) : zStationChange(val)
            }
          "
        />
        <!-- Z端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          class="ml-10 mb-10"
          style="width: 280px"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'Z_END_STATION_NAME' : 'A_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? zStationChange(val) : aStationChange(val)
            }
          "
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
      <div class="mb-10 flex">
        <el-button
          v-if="permission.open && pageName === 'manager'"
          type="primary"
          icon="el-icon-plus"
          @click="operate({ data: null, type: 'add' })"
        >{{ $t('INTELLIGENT_CONNECT') }}</el-button>
        <el-button
          v-if="
            (permission.bulkexport && pageName === 'manager') ||
              (backupPermission.bulkexport && pageName === 'backup')
          "
          type="primary"
          :disabled="!selectedRow.length"
          @click="$debounce(exportBiz, 'select')"
        >{{ $t('BULK_EXPORT') }}</el-button>
        <el-button
          v-if="
            (permission.allexport && pageName === 'manager') ||
              (backupPermission.allexport && pageName === 'backup')
          "
          type="primary"
          @click="$debounce(exportBiz, 'all')"
        >{{ $t('EXPORT_ALL') }}</el-button>
      </div>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :cell-class="cellClass"
      :operate-width="pageName === 'manager' ? 310 : 90"
      :options="{ seletion: true }"
      @sortChange="sortChange"
      @operate="operate"
      @pageChange="pageChange"
      @selectionChange="selectionChange"
    />
  </div>
</template>

<script>
  import mixin from '@/mixin/bizListMixin'
  import { mapGetters } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import exportApi from '@/api/oen/ExportApi'
  import { downloadFile, getParentsById } from '@/utils/common'
  import RegionCascader from '@/components/RegionCascader'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    components: {
      RegionCascader,
      TableView
    },
    mixins: [mixin],
    props: {
      pageName: {
        type: String,
        default: ''
      }
    },
    inject: ['functionName'],
    data() {
      return {
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        queryData: {
          keyword: '',
          startStationIdList: [],
          endStationIdList: [],
          bizStatus: '',
          stationIdList: []
        },
        selectedIds: [],
        stationType: '',
        tableData: [],
        sortData: {
          field: null,
          type: null
        },
        selectedRow: []
      }
    },
    computed: {
      ...mapGetters(['baseRegionList', 'dictMap', 'dictList', 'getUserId', 'stationTree']),
      permission() {
        return this.$store.getters.getAuthData('biz:manager')
      },
      backupPermission() {
        return this.$store.getters.getAuthData('biz:backup')
      }
    },
    activated() {
      // 10秒刷新页面
      this.loadData(true)
    },
    deactivated() {
      this.timingGetList(false)
    },
    beforeDestroy() {
      this.timingGetList(false)
    },
    methods: {
      timingGetList(timing = true) {
        // 30秒刷新页面
        const that = this
        this.intervalTimer && clearTimeout(this.intervalTimer)
        this.intervalTimer = null
        if (!timing) return
        this.intervalTimer = setTimeout(() => {
          that.loadData(true)
        }, 30 * 1000)
      },
      sortChange(data) {
        this.sortData = data
        this.loadData()
      },
      // 获取操作按钮
      getBtns(row) {
        const unlocked =
          !row.bizChannelList.some(i => i.lockStatus === 'LOCKED') &&
          this.regionAuthor(row) &&
          this.pageName === 'manager'
        const bizStatus = row.bizChannelList.map(i => i.bizStatus)
        const managerBtn = [
          {
            key: 'channel', // 查看通道
            show: this.pageName === 'manager' && this.permission.channel,
            label: 'CHANNEL'
          },
          {
            key: 'mod', // 修改名称
            show: unlocked && this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'restore', // 恢复
            show: this.getBtnShow(row, unlocked, bizStatus, 'restore'),
            label: 'INTELLIGENCE_RECOVERY'
          },

          {
            key: 'restore', // 重新恢复
            show: this.getBtnShow(row, unlocked, bizStatus, 'toRestore'),
            label: 'TO_RESTORE'
          },
          {
            key: 'reduction', // 智能还原
            show: this.getBtnShow(row, unlocked, bizStatus, 'reduction'),
            label: 'REDUCTION'
          },
          {
            key: 'otdrTest', // OTDR测试
            show: this.getOtdrTestBtn(row, unlocked, bizStatus, 'otdrTest'),
            label: 'BIZ_FUNC_OTDR_TEST'
          },
          {
            key: 'otdrTestResult', // OTDR测试记录
            show: this.getOtdrTestBtn(row, unlocked, bizStatus, 'otdrTestResult'),
            label: 'BIZ_FUNC_OTDR_TEST_RESULT'
          },
          {
            key: 'setFault', // 设为故障
            show:
              unlocked &&
              bizStatus.every(i => ['RESTORE', 'NORMAL'].includes(i)) &&
              this.permission.setFault,
            label: 'SET_FAIL'
          },
          {
            key: 'faultLocation', // 故障定位
            show:
              unlocked &&
              this.permission.faultLocation &&
              bizStatus.every(i => i === 'RESTORE') &&
              row.openType !== 'INDEPENDENT',
            label: 'FAULT_LOCATION'
          },

          {
            key: 'trouble_solved', // 故障已排除
            show: unlocked && bizStatus.every(i => i === 'FAULT') && this.permission.faultsolved,
            label: 'TROUBLE_SOLVED'
          },
          {
            key: 'del', // 删除
            show: unlocked && this.permission.del,
            disabled:
              bizStatus.some(i => ['OPENING', 'RESTORING', 'RETURNING'].includes(i)) && unlocked,
            label: 'DEL'
          },
          {
            key: 'view', // 查看备用通道
            show: this.pageName === 'backup' && row.openType !== 'INDEPENDENT',
            label: 'VIEW'
          },
          {
            key: 'mod', // 配置备用
            show: this.getBackBtn(row),
            disabled: bizStatus.some(i =>
              ['OPENING', 'RESTORING', 'RETURNING', 'OPEN_FAIL'].includes(i)
            ),
            label: 'CONFIG'
          }
        ]
        return managerBtn.filter(i => i.show)
      },
      getBtnShow(row, unlocked, bizStatus, key) {
        let visiable = false
        switch (key) {
        case 'restore':
          visiable =
            unlocked &&
            row.openType !== 'INDEPENDENT' &&
            bizStatus.every(i => ['FAULT', 'REDUCTION_FAIL', 'RETURN_FAIL'].includes(i)) &&
            this.permission.restore
          break
        case 'toRestore':
          visiable = unlocked && bizStatus.includes('RESTORE_FAIL') && this.permission.restore
          break
        case 'reduction':
          visiable =
            unlocked &&
            bizStatus.every(i => i === 'RESTORE') &&
            this.permission.reduction &&
            row.bizLevel === 'IMPORTANT'
          break
        default:
          visiable = false
        }
        return visiable
      },
      getOtdrTestBtn(row, unlocked, bizStatus) {
        return (
          this.pageName === 'manager' &&
          row.openType !== 'INDEPENDENT' &&
          (bizStatus.every(i => ['RESTORE', 'NORMAL'].includes(i)) ||
            bizStatus.includes('FAULT')) &&
          unlocked &&
          this.permission.otdrtest
        )
      },
      getBackBtn(row) {
        return (
          this.pageName === 'backup' &&
          this.backupPermission.mod &&
          this.regionAuthor(row) &&
          row.openType !== 'INDEPENDENT'
        )
      },
      loadData(hideLoading = false) {
        const queryData = {
          ...searchData,
          sort: this.sortData.type ? this.sortData : null
        }
        // console.log('queryData', queryData)
        queryData.bizStatus = queryData.bizStatus || null
        bizOpenApi
          .queryPage(queryData, { ...this.pageData, hideLoading: hideLoading })
          .then(res => {
            const statusSort = [
              'FAULT',
              'OPEN_FAIL',
              'RESTORE_FAIL',
              'REDUCTION_FAIL',
              'RETURN_FAIL',
              'OPENING',
              'RESTORING',
              'RETURNING',
              'RESTORE',
              'NORMAL'
            ]
            const listData = res.list || []
            listData.forEach(i => {
              i.startStationName = this.getRegionName(i.startStationId)
              i.endStationName = this.getRegionName(i.endStationId)
              i.startRoomName = this.getRoomName(i.startNode.roomId)
              i.endRoomName = this.getRoomName(i.endNode.roomId)
              i.resourceCodeName = i.resourceCode || '--'
              const statusIndex = i.bizChannelList.map(z =>
                statusSort.findIndex(j => j === z.bizStatus)
              )
              i.bizStatus = statusSort[Math.min(...statusIndex)]
              i.btns = this.getBtns(i)
            })
            if (!this.sortData.type) {
              // 当前页面数据排序 1根据时间倒序排序2.优先把故障业务排在前面
              listData
                .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                .sort((a, b) => {
                  a.bizStatus === 'FAULT' ? 1 : 0
                  b.bizStatus === 'FAULT' ? 1 : 0
                  const aNum = a.bizStatus === 'FAULT' ? 1 : 0
                  const bNum = b.bizStatus === 'FAULT' ? 1 : 0
                  return bNum - aNum
                })
            }
            this.tableData = listData
            this.pageData.total = res.total
            this.timingGetList(true)
          })
      },
      cellClass({ row, column }) {
        const statusColor = [
          {
            value: 'fault',
            keys: ['FAULT']
          },
          {
            value: 'doing',
            keys: [
              'OPENING',
              'RESTORING',
              'RETURNING',
              'OPEN_FAIL',
              'RESTORE_FAIL',
              'REDUCTION_FAIL',
              'RETURN_FAIL'
            ]
          },
          {
            value: 'normal',
            keys: ['RESTORE', 'NORMAL']
          }
        ]
        if (column.property === 'bizStatus') {
          const colorData = statusColor.find(i => i.keys.includes(row.bizStatus))
          return 'color-' + (colorData ? colorData.value : 'normal')
        }
      },
      // 修改业务状态
      operateStatus(data, status) {
        this.$confirm(this.$t(status === 'fault' ? 'CONFIRM_BIZ_FAULT' : 'CONFIRM_BIZ_NORMAL'), {
          type: 'warning'
        })
          .then(() => {
            const apiPost = status === 'fault' ? 'bizFault' : 'bizNormal'
            bizOpenApi[apiPost]({
              bizId: data.bizId,
              bizName: data.bizName,
              functionName: this.functionName
            }).then(res => {
              if (res) {
                this.loadData()
                this.$message.closeAll()
                this.$message.success(this.$t('MODIFY_SUCCESS'))
              }
            })
          })
          .catch(() => {})
      },
      // 获取区域/站点
      getRegionName(regionId) {
        const parents = getParentsById(this.stationTree, regionId, 'regionId') || []
        return parents
          .reverse()
          .map(i => i.regionName)
          .join('/')
      },
      // 机房
      getRoomName(roomId) {
        if (!roomId) return ''
        const stationData = this.baseRegionList.find(i => i.regionId === roomId)
        return stationData ? stationData.regionName : ''
      },
      // 区域搜索条件改变
      aStationChange(data) {
        this.queryData.startStationIdList = data
      },
      zStationChange(data) {
        this.queryData.endStationIdList = data
      },
      stationChange(data) {
        this.queryData.stationIdList = data
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        this.queryData.keyword = this.queryData.keyword.trim()
        searchData = { ...this.queryData }
        this.loadData()
      },
      // 执行恢复前校验，如果业务正在还原，就不能执行恢复操作
      checkRestore(row) {
        bizOpenApi.reductionInfo({ bizId: row.bizId }).then(res => {
          if (res) {
            this.$message.error(this.$t('NOT_RESTORE'))
          } else {
            const operateData = {
              data: row,
              type: 'restore'
            }
            this.$emit('operate', operateData)
          }
        })
      },
      // 按钮操作
      operate(data) {
        switch (data.type) {
        case 'restore':
          this.$debounce(this.checkRestore, data.data)
          break
        case 'setFault':
          this.operateStatus(data.data, 'fault')
          break
        case 'trouble_solved':
          this.operateStatus(data.data, 'normal')
          break
        case 'del':
          this.del(data.data)
          break
        default:
          this.$emit('operate', data)
          break
        }
      },
      // 删除
      del(row) {
        this.$confirm(
          this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('BUSINESS'), value: row.bizName }),
          {
            type: 'warning'
          }
        )
          .then(() => {
            bizOpenApi
              .delByBizId({
                bizId: row.bizId,
                bizName: row.bizName,
                functionName: this.functionName
              })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('DELETE_SUCCESS'))
                  this.loadData()
                }
              })
          })
          .catch(() => {})
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      },
      selectionChange(val) {
        this.selectedRow = val
      },
      exportBiz(type) {
        let apiFun = 'bizInfo'
        let fileName = this.$t('BIZ_LIST')
        if (this.pageName === 'backup') {
          apiFun = 'bizBackInfo'
          fileName = this.$t('MENU_BACKUP_MANAGER')
        }
        const queryData = { bizIdList: ' ', type: 'all', operateResult: true }
        if (type !== 'all') {
          queryData.type = ''
          queryData.bizIdList = this.selectedRow.map(i => i.bizId).join()
        }
        exportApi[apiFun](queryData).then(res => {
          downloadFile(res, fileName)
        })
      },
      // 区域权限判断控制
      regionAuthor(row) {
        return (
          (this.baseRegionList.some(i => i.regionId === row.startStationId) &&
            this.baseRegionList.some(i => i.regionId === row.endStationId)) ||
          this.getUserId === 'admin'
        )
      }
    }
  }
</script>
